<template>
  <div>
    <video ref="videoPlayer" controls muted></video>
    <div v-if="errorMessage" class="loading-cls">正在加载视频...</div>
    <!-- <div v-if="isEnded">视频播放结束，正在重连...</div>  -->
    <!-- <div v-if="loading">正在加载视频...</div>  -->
  </div>
</template>

<script>
import { onMounted, onBeforeUnmount, ref } from 'vue';

export default {
  setup () {
    const videoPlayer = ref(null);
    const flvPlayer = ref(null);
    const errorMessage = ref(''); // 用于存储错误信息
    const isEnded = ref(false); // 用于指示视频是否播放结束
    const loading = ref(false); // 用于指示加载状态
    const lastDecodedFrames = ref(0);
    let retryCount = 0; // 当前重试次数
    const maxRetries = 20; // 最大重试次数
    const destroyFlv = () => {
      if (flvPlayer.value) {
        flvPlayer.value.pause();
        flvPlayer.value.unload();
        flvPlayer.value.detachMediaElement();
        flvPlayer.value.destroy();
        flvPlayer.value = null;
      }
    }
    const loadVideo = () => {
      console.log('isSupported:111111 ');
      // console.log('isSupported: ' + flvjs.isSupported());
      // console.log(flvjs);
      if (flvjs.isSupported()) {
        console.log('创建 flvPlayer', flvjs);
        flvPlayer.value = flvjs.createPlayer({
          type: 'flv',
          url: `http://192.168.1.225:8101/test1/test1.live.flv`
        });
        console.log("flv实例", flvPlayer.value);
        flvPlayer.value.attachMediaElement(videoPlayer.value);

        flvPlayer.value.on(flvjs.Events.METADATA_ARRIVED, () => {
          console.log('元数据已加载，开始播放');
          flvPlayer.value.play();
        });

        flvPlayer.value.on(flvjs.Events.MEDIA_INFO, () => {
          console.log('测试事件：MEDIA_INFO');
        });

        flvPlayer.value.on(flvjs.Events.MEDIA_SOURCE_ENDED, () => {
          console.log('自定义测试事件：MEDIA_SOURCE_ENDED');
        });

        // 监听错误事件 
        flvPlayer.value.on(flvjs.Events.ERROR, (err, errdet) => {
          // 参数 err 是一级异常，errdet 是二级异常 
          if (err == flvjs.ErrorTypes.MEDIA_ERROR) {
            console.log('媒体错误')
            if (errdet == flvjs.ErrorDetails.MEDIA_FORMAT_UNSUPPORTED) {
              console.log('媒体格式不支持')
            }
          }
          if (err == flvjs.ErrorTypes.NETWORK_ERROR) {
            console.log('网络错误')
            if (errdet == flvjs.ErrorDetails.NETWORK_STATUS_CODE_INVALID) {
              console.log('http状态码异常')
            }
          }
          if (err == flvjs.ErrorTypes.OTHER_ERROR) {
            console.log('其他异常：', errdet)
          }
          handleReconnect()
        })
        // flvPlayer.value.on(flvjs.Events.ERROR, (errorType, errorDetails) => {
        //   errorMessage.value = `错误类型: ${errorType}, 错误详情: ${errorDetails}`;
        //   console.error(`错误发生: ${errorType}, 详情: ${errorDetails}`);
        // });

        flvPlayer.value.on(flvjs.Events.END, () => {
          console.log('视频播放结束');
          handleReconnect();
        });

        flvPlayer.value.on(flvjs.Events.MEDIA_SOURCE_ENDED, () => {
          console.log('测试自定义事件->媒体源结束时触发');
          handleReconnect();
        });

        flvPlayer.value.on(flvjs.Events.RECOVERED_EARLY_EOF, (res) => {
          console.log('文件结束,某部分数据不完整或者丢失', res);
        });

        flvPlayer.value.on(flvjs.Events.STATISTICS_INFO, (res) => {
          console.log('视频播放信息:', res);
          if (lastDecodedFrames.value === 0) {
            lastDecodedFrames.value = res.decodedFrames
            return
          }
          console.log('res.decodedFrames->', res.decodedFrames);
          if (res.decodedFrames > 0) {
            lastDecodedFrames.value = res.decodedFrames
            console.log(`视频播放正常,解码帧数为${res.decodedFrames} `);
          } else {
            console.log('视频断流,重连中...');
            lastDecodedFrames.value = res.decodedFrames
            destroyFlv()
            handleReconnect()
          }
          res.decodedFrames
        });
        flvPlayer.value.load();
        loading.value = true;
        console.log('视频加载中...');
      } else {
        console.error('当前浏览器不支持 flv.js');
      }
    };

    const handleReconnect = () => {
      console.log('正在进行断线重连');
      if (retryCount < maxRetries) {
        isEnded.value = true;
        const delay = Math.pow(2, retryCount) * 1000; // 指数退避策略
        setTimeout(() => {
          retryCount++;
          console.log(`重新加载视频，尝试次数: ${retryCount} `);
          loadVideo();
          isEnded.value = false;
        }, delay);
      } else {
        errorMessage.value = '无法连接视频，请稍后再试。';
        console.log('达到最大重试次数，停止重连。');
      }
    };

    onMounted(() => {
      console.log('组件挂载，开始加载视频');
      loadVideo();
    });

    onBeforeUnmount(() => {
      if (flvPlayer.value) {
        console.log('销毁 flvPlayer');
        flvPlayer.value.destroy();
      }
    });

    return {
      videoPlayer,
      errorMessage,
      isEnded,
      loading
    };
  }
};
</script>

<style>
/* 添加一些样式 */
video {
  width: 100%;
  height: auto;
}

.loading-cls {
  position: absolute;
  top: 65%;
  left: 35%;
}
</style>
